
var util = require("util");

var npm_repo = require("./npm_repo.js");
var eventproxy = require(npm_repo("eventproxy"));

var db = require("./db.js");
var users = require("./users.js");
var httpclient = require("./httpclient.js");

var weibo = {};

weibo.cache = function(uid, weibos){
	if (weibos.length === 0)
	{
		return;
	}

	let user = users.get(uid);
	let max_weibo_id = weibos[0].id;
	let min_weibo_id = weibos[weibos.length-1].id;
	
	let sqls = [];
	for (let w of weibos)
	{
		let sql = util.format("INSERT INTO cache_weibos VALUES(%d,%d,\"%s\",\"%s\",%d,%d,%d,\"%s\")",
				w.id, uid, w.poster_name, w.poster_icon, w.post_date, w.reposts_count, w.comments_count, w.content);
		sqls.push(sql);
	}

	if (user.max_weibo_id < max_weibo_id)
	{
		user.max_weibo_id = max_weibo_id;
		
		let sql = util.format("UPDATE users SET max_weibo_id=%d WHERE uid=%d", max_weibo_id, uid);
		//console.log(sql);
		sqls.push(sql);
	}
	if (user.min_weibo_id === 0 || user.min_weibo_id > min_weibo_id)
	{
		user.min_weibo_id = min_weibo_id;
		
		let sql = util.format("UPDATE users SET min_weibo_id=%d WHERE uid=%d", min_weibo_id, uid);
		//console.log(sql);
		sqls.push(sql);
	}
	db.exec(sqls);
};

weibo.load = function(uid){
	return new Promise(function(resolve, reject){
		let user = users.get(uid);
		if (undefined === user)
		{
			reject("no_valid_user_token");
			return;
		}

		let ep = eventproxy.create("latest", "cache", function(weibos_latest, weibos_cache){
			let weibos = weibos_latest.concat(weibos_cache);
			resolve(weibos);
		});

		/********************************************************************************/
		
		if (false)
		{
			let u = ["https://api.weibo.com/2/statuses/friends_timeline.json?access_token="+ user.token,
					 "count=25",
					].join("&");
			httpclient.get(u, function(data){
				let result = JSON.parse(data);
				if (result.total_number === 0)
				{
					ep.emit("latest", []);
					return;
				}

				let weibos = [];
				for (let status of result.statuses)
				{
					weibos.push({
						id: status.id,
						poster_name: status.user.screen_name,
						poster_icon: status.user.profile_image_url,
						post_date: new Date(status.created_at).getTime(),
						reposts_count: status.reposts_count,
						comments_count: status.comments_count,
						content: status.text
					});
				}

				ep.emit("latest", weibos);
				weibo.cache(uid, weibos);
			});
		}

		/********************************************************************************/
		
		let sql = "SELECT id,poster_name,poster_icon,post_date,reposts_count,comments_count,content FROM cache_weibos WHERE uid="+ uid + " ORDER BY id DESC LIMIT 75";
		db.query(sql).then(function(result){
			ep.emit("cache", result);
			ep.emit("latest", []);
		}, function(){
			ep.emit("cache", []);
		});
	});
};

weibo.refresh = function(uid, min_weibo_id){
	return new Promise(function(resolve, reject){
		let user = users.get(uid);
		if (undefined === user)
		{
			reject("no_valid_user_token");
			return;
		}

		let u = ["https://api.weibo.com/2/statuses/friends_timeline.json?access_token="+ user.token,
				 "since_id="+min_weibo_id,
				 "count=25",
				].join("&");
		httpclient.get(u, function(data){
			let result = JSON.parse(data);
			if (result.total_number === 0)
			{
				resolve([]);
				return;
			}

			let weibos = [];
			for (let status of result.statuses)
			{
				weibos.push({
					id: status.id,
					poster_name: status.user.screen_name,
					poster_icon: status.user.profile_image_url,
					post_date: new Date(status.created_at).getTime(),
					reposts_count: status.reposts_count,
					comments_count: status.comments_count,
					content: status.text
				});
			}

			resolve(weibos);
			weibo.cache(uid, weibos);
		});
	});
};

weibo.loadmore = function(uid, max_weibo_id){
	return new Promise(function(resolve, reject){
		let user = users.get(uid);
		if (undefined === user)
		{
			reject("no_valid_user_token");
			return;
		}

		if (user.min_weibo_id >= max_weibo_id)
		{
			let u = ["https://api.weibo.com/2/statuses/friends_timeline.json?access_token="+ user.token,
					 "max_id ="+max_weibo_id-1,
					 "count=25",
					].join("&");
			httpclient.get(u, function(data){
				let result = JSON.parse(data);
				if (result.total_number === 0)
				{
					resolve([]);
					return;
				}

				let weibos = [];
				for (let status of result.statuses)
				{
					weibos.push({
						id: status.id,
						poster_name: status.user.screen_name,
						poster_icon: status.user.profile_image_url,
						post_date: new Date(status.created_at).getTime(),
						reposts_count: status.reposts_count,
						comments_count: status.comments_count,
						content: status.text
					});
				}

				resolve(weibos);
				weibo.cache(uid, weibos);
			});
		}
		else
		{
			let sql = util.format("SELECT id,poster_name,poster_icon,post_date,reposts_count,comments_count,content FROM cache_weibos WHERE uid=%d ORDER BY id DESC LIMIT 75", 
				uid);
		}
	});
};

module.exports = weibo;
